<template>
  <div class="tree-item">
    <div class="title">
      知识库
      <el-button type="text" v-if="role === 'admin'" @click="() => openDialog('')">+</el-button>
    </div>
    <el-tree
      :data="data"
      node-key="id"
      default-expand-all
      @node-click="handleNodeClick"
      :expand-on-click-node="false"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span style="margin-right: 20px">{{ node.label }}</span>
        <span>
          <el-button type="text" v-if="role === 'admin'" @click="() => openDialog(data)"
            >+</el-button
          >
          <el-button type="text" v-if="role === 'admin'" @click="() => deleteNode(node, data)"
            >-</el-button
          >
        </span>
      </span>
    </el-tree>
    <!-- 新建 -->
    <el-dialog
      title="新建目录"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form :model="form">
        <el-form-item label="上级目录">
          <el-input v-model="form.parent" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="目录名称">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getData, postData, deleteData } from '@/service/getData';
export default {
  name: 'TreeItem',
  data() {
    return {
      data: [],
      role: 'user', // 用户角色
      dialogVisible: false,
      saveObj: {},
      form: {
        name: '',
        parent: '',
        id: '',
      },
    };
  },
  mounted() {
    if (this.$store.state.user.groups[0]) {
      this.getTree();
      switch (this.$store.state.user.groups[0].name) {
        case '超级管理员':
          this.role = 'admin';
          break;
        case '管理员':
          this.role = 'admin';
          break;
        default:
          this.role = 'user';
          break;
      }
    }
  },
  methods: {
    //  获取树结构数据
    getTree() {
      // 超级管理员 获取全部 文件树
      getData(`api/knowledge_base/files/?user_id=${this.$store.state.user.id}`).then((res) => {
        this.data = res;
        // 递归遍历数组，给每个对象添加label属性
        const traverse = (arr) => {
          arr.forEach((item) => {
            item.label = item.name;
            if (item.children && item.children.length > 0) {
              traverse(item.children);
            }
          });
        };
        traverse(this.data);

        // 默认会将第一个目录展开
        if (this.saveObj) {
          // 递归遍历数组，找到id对应的对象，并将专递给父组件
          const findObj = (arr) => {
            arr.forEach((item) => {
              if (item.id === this.saveObj.id) {
                this.$emit('node-click', item);
              }
              if (item.children && item.children.length > 0) {
                findObj(item.children);
              }
            });
          };
          findObj(this.data);
        }
      });
    },

    openDialog(obj) {
      if (obj) {
        this.form.parent = obj.name;
        this.form.id = obj.id;
        this.dialogVisible = true;
      } else {
        this.form.parent = '根目录';
        this.form.id = '';
        this.dialogVisible = true;
      }
    },
    // 新增
    add() {
      if (!this.form.name) {
        this.$message({
          type: 'warning',
          message: '请输入目录名称！',
        });
        return;
      }

      postData('api/knowledge_base/folders/', {
        name: this.form.name,
        parent: this.form.id,
      })
        .then((res) => {
          this.$message({
            type: 'success',
            message: '添加成功！',
          });

          this.getTree();
          this.form.name = '';
          this.form.id = '';
          this.form.parent = '';
          this.dialogVisible = false;
        })
        .catch((err) => {
          this.$message({
            type: 'error',
            message: '添加失败！',
          });
        });
    },
    handleClose() {
      this.dialogVisible = false;
    },
    // 删除
    deleteNode(node, data) {
      this.$confirm('此操作将永久删除该目录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteData(`api/knowledge_base/folders/${data.id}/`)
          .then((res) => {
            this.$message.success('删除成功！');
            this.$emit('node-delete');
            this.getTree();
          })
          .catch((err) => {
            this.$message.success('删除成功！');
            this.$emit('node-delete');
            this.getTree();
          });
      });
    },
    // 修改
    handleNodeClick(data) {
      this.saveObj = data;
      //将选中的目录信息传递给父组件进行处理
      this.$emit('node-click', data);
    },
  },
};
</script>
<style lang="scss" scoped>
.title {
  text-align: center;
  font-size: 16px;
  margin-bottom: 10px;
  line-height: 40px;
  color: #5993ff;
  background-color: #e5f3ff;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
>
